package com.markhsiu.minimq.message;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import com.markhsiu.minimq.core.exeption.MiniMQException;
import com.markhsiu.minimq.message.constant.MessageCmdEnum;

/**
 * 请求响应结果
 * @author Mark Hsiu
 *
 */
public class Result {

	private Message message;//消息内容
	private Integer error = 0;// 0 :正确  1 :错误或异常
	//监听消息
	private final CountDownLatch downLatch = new CountDownLatch(1);

	public Message getMessage() {
		return message;
	}

	public void setMessage(Message message) {
		this.message = message;
	}

	public Integer getError() {
		return error;
	}

	public void setError(Integer error) {
		this.error = error;
	}

	public Message getMessageResult(long timeout, TimeUnit unit) {
		try {
			downLatch.await(timeout, unit);
		} catch (InterruptedException e) {
			throw new MiniMQException();
		} finally {
			downLatch.countDown();
		}

		if (error == 1) {
			return null;
		}
		return message;
	}

	public void release() {
		downLatch.countDown();
	}
	
	public boolean check(){
		return this.getError() == 0 && this.getMessage().getCmd() == MessageCmdEnum.SUCCESS;
	}

	@Override
	public String toString() {
		return String.format("error:%s message:%s ", error, message.toString());
	}

}
